package com.huikeportal.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huikeportal.controller.common.MessageManager;
import com.huikeportal.dao.AspnetRolesMapper;
import com.huikeportal.dao.LoginMapper;
import com.huikeportal.dao.PrivilegeRolesAuthorityMapper;
import com.huikeportal.dao.RoleMapper;
import com.huikeportal.model.AspnetRoles;
import com.huikeportal.model.MenuInfo;
import com.huikeportal.model.MessageCommon;
import com.huikeportal.model.PrivilegeRolesAuthority;
import com.huikeportal.model.RoleInfo;
import com.huikeportal.model.RolePageButton;
import com.huikeportal.model.TreeHtml;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.RoleService;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

	@Autowired
	private LoginMapper loginMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private AspnetRolesMapper aspnetRolesMapper;

	@Autowired
	private PrivilegeRolesAuthorityMapper privilegeRolesAuthorityMapper;

	// 树节点深度
	private int loop = -1;

	// 角色列表的条数
	private int size = 0;

	/**
	 * 树节点空格数
	 * 
	 * @param loop
	 * @return
	 */
	private String space(int loop) {
		String space = "";
		for (int i = 0; i < loop; i++) {
			space += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		}
		return space;
	}

	/**
	 * 根据角色id查询该角色对应页面按钮权限
	 */
	public List<RolePageButton> getButtonHtml(UserInfo userInfo, String roleId)
			throws Exception {
		// 初始化不显示页面按钮权限信息
		if (roleId != null) {
			userInfo = loginMapper.getUserByName(userInfo);
			// 获取当前登录角色拥有的最大页面权限
			List<RolePageButton> loginRoleList = roleMapper
					.getButtonById(userInfo.getRoleId());
			// 获取当前点击的角色拥有的页面权限
			List<RolePageButton> clickRoleList = roleMapper
					.getButtonById(roleId);
			// 设置初始化选中
			for (int i = 0; i < loginRoleList.size(); i++) {
				// 设置按钮名称
				loginRoleList.get(i).setOperationName(
						getButtonName(loginRoleList.get(i).getOperationId()
								.toString(), userInfo.getSysLang()));
				for (int j = 0; j < clickRoleList.size(); j++) {
					// 设置按钮页面上显示id
					loginRoleList.get(i).setOprateId(
							loginRoleList.get(i).getMenuId() + "_"
									+ loginRoleList.get(i).getOperationId());
					// 如果当前点击的角色拥有该权限，则设置选中
					if (clickRoleList.get(j).getMenuId().equals(
							loginRoleList.get(i).getMenuId())
							&& clickRoleList.get(j).getOperationId().equals(
									loginRoleList.get(i).getOperationId())) {
						loginRoleList.get(i).setIsChecked("Y");
					}
				}
			}
			return loginRoleList;
		}
		return null;
	}

	/**
	 * 获取页面信息
	 * 
	 * @param flag
	 * @return
	 * @throws Exception
	 */
	public List<MenuInfo> getPageInfo(String flag,
			List<RolePageButton> roleHtml, String sysLang) throws Exception {
		List<MenuInfo> resultList = new ArrayList<MenuInfo>();
		if ("1".equals(flag)) {
			List<MenuInfo> oneList = loginMapper.getMenuList(sysLang);
			if ("".equals(roleHtml) || roleHtml == null) {
				return oneList;
			}
			for (int i = 0; i < oneList.size(); i++) {
				for (int j = 0; j < roleHtml.size(); j++) {
					if (oneList.get(i).getMenuId() == roleHtml.get(j)
							.getParentId()) {
						resultList.add(oneList.get(i));
						break;
					}
				}
			}
			// 菜单过滤
			return resultList;
		} else if ("2".equals(flag)) {
			List<MenuInfo> twoList = loginMapper.getChildMenuList(sysLang);
			if ("".equals(roleHtml) || roleHtml == null) {
				return twoList;
			}
			for (int i = 0; i < twoList.size(); i++) {
				for (int j = 0; j < roleHtml.size(); j++) {
					if (twoList.get(i).getMenuId().equals(
							roleHtml.get(j).getMenuId())) {
						resultList.add(twoList.get(i));
						break;
					}
				}
			}
			// 菜单过滤
			return resultList;
		} else {
			return null;
		}
	}

	/**
	 * 获取按钮名称
	 * 
	 * @param buttonId
	 * @return
	 * @throws Exception
	 */
	private String getButtonName(String buttonId, String sysLang)
			throws Exception {
		SqlParameter sql = new SqlParameter();
		sql.setString("hkcloud_page_button");
		sql.setSysLang(sysLang);
		List<WordBook> bookList = roleMapper.getButtonInfo(sql);
		for (int i = 0; i < bookList.size(); i++) {
			if (buttonId.equals(bookList.get(i).getDicCode())) {
				return bookList.get(i).getDicValue();
			}
		}
		return "";
	}

	/**
	 * 根据登录用户查询该用户所有角色列表
	 */
	public String getRoleTreeHtml(UserInfo userInfo, String roleId)
			throws Exception {
		// 获取用户详细信息
		userInfo = loginMapper.getUserByName(userInfo);
		// 根据用户id查询对应角色表主键id
		Long id = roleMapper.getRoleIdByUser(userInfo.getUserId());
		userInfo.setId(id);
		List<TreeHtml> roleList = roleMapper.getRoleById(userInfo);
		size = roleList.size();
		roleList = getFloor(roleList);
		return createTreeHtml(roleList, userInfo.getId(), roleId);
	}

	/**
	 * 获取每一层树节点的层数
	 * 
	 * @param floorList
	 * @return
	 */
	private List<TreeHtml> getFloor(List<TreeHtml> floorList) {
		for (int i = 0; i < floorList.size(); i++) {
			// 如果未处理
			if (!floorList.get(i).isDeal()) {
				loop = -1;
				int k = getFl(floorList, floorList.get(i));
				floorList.get(i).setFloorNum(k);
				// 将该节点设为已处理
				floorList.get(i).setDeal(true);
				size--;
			}
		}
		return floorList;
	}

	/**
	 * 递归获取树节点深度
	 * 
	 * @param floorList
	 * @param treeHtml
	 * @return
	 */
	private int getFl(List<TreeHtml> floorList, TreeHtml treeHtml) {
		loop++;
		// 如果当前处理的节点不是根节点，则继续处理他的父节点
		if (treeHtml.getParentId() != 0) {
			for (int i = 0; i < floorList.size(); i++) {
				if (treeHtml.getParentId() == floorList.get(i).getId()) {
					treeHtml = floorList.get(i);
					return getFl(floorList, treeHtml);
				}
			}
		}
		return loop;
	}

	/**
	 * 根据角色列表生成html
	 * 
	 * @param roleList
	 *            当前用户拥有的角色清单(包含其下级角色创建的角色清单)
	 * @param id
	 *            当前用户拥有的主角色
	 * @return
	 */
	private String createTreeHtml(List<TreeHtml> roleList, Long id,
			String roleId) {
		// 全部树节点存储容器
		Map<String, TreeHtml> allMap = new HashMap<String, TreeHtml>();
		// 全部子节点列表存储容器
		Map<String, TreeHtml> childMap = new HashMap<String, TreeHtml>();
		String treeHtml = "";
		// 如果当前用户只有一个角色
		if (roleList.size() == 1) {
			treeHtml += "<li><a class='marr' href='javascript:treeClick("
					+ "\"" + roleList.get(0).getRoleId() + "\"" + ")'>"
					+ roleList.get(0).getRoleName() + "</a></li>";
		}
		// 如果当前用户有下级角色
		else {
			for (int i = 0; i < roleList.size(); i++) {
				allMap.put(roleList.get(i).getId().toString(), roleList.get(i));
			}
			// 生成根节点html
			TreeHtml rootHtml = new TreeHtml();
			rootHtml.setId(id);
			// 循环角色列表，合并，并删除allMap中的值
			while (allMap.size() > 1) {
				for (int i = 0; i < roleList.size(); i++) {
					// 根节点不处理
					if (!id.equals(roleList.get(i).getId())) {
						// 如果该节点还未被处理过
						if (allMap.containsKey(roleList.get(i).getId()
								.toString())) {
							// 从allMap中获取该节点的最新信息
							TreeHtml childHtml = allMap.get(roleList.get(i)
									.getId().toString());
							// 如果该节点是叶子，将其父节点放入容器中，且将其父节点变成叶子
							if (childHtml.isLeaf()) {
								TreeHtml fatherHtml = new TreeHtml();
								// 找到其父节点
								for (int j = 0; j < roleList.size(); j++) {
									if (childHtml.getParentId().equals(
											roleList.get(j).getId())) {
										fatherHtml = roleList.get(j);
										break;
									}
								}
								String fatherKey = fatherHtml.getId()
										.toString();
								// 如果该父节点还未在容器中，则加入，并更改状态
								if (!childMap.containsKey(fatherKey)) {
									fatherHtml.setLeaf(true);
									List<TreeHtml> chiList = new ArrayList<TreeHtml>();
									chiList.add(childHtml);
									fatherHtml.setChildHtml(chiList);
									childMap.put(fatherHtml.getId().toString(),
											fatherHtml);

								}
								// 如果该父节点已经在容器中，则加入其子节点集合中
								else {
									fatherHtml = childMap.get(fatherKey);
									List<TreeHtml> chiList = fatherHtml
											.getChildHtml();
									chiList.add(childHtml);
									childMap.remove(fatherKey);
									childMap.put(fatherHtml.getId().toString(),
											fatherHtml);
								}
								allMap.remove(childHtml.getId().toString());
							}
						}
					}
				}
			}
			// 获取根节点信息，生成html
			TreeHtml root = allMap.get(id.toString());
			treeHtml += createChildHtml(root, roleId);
		}
		return treeHtml;
	}

	/**
	 * 递归生成treehtml
	 * 
	 * @param tree
	 * @return
	 */
	private String createChildHtml(TreeHtml tree, String roleId) {
		String html = "";
		if (tree.getChildHtml() != null) {
			if (tree.getRoleId().equals(roleId)) {
				html += "<ul><li>"
						+ space(tree.getFloorNum())
						+ "<img id='img"
						+ tree.getId()
						+ "' src='images/1.jpg' onclick='showhide("
						+ tree.getId()
						+ ")'><a class='marr selecteda' href='javascript:treeClick("
						+ "\"" + tree.getRoleId() + "\"" + ")'>"
						+ tree.getRoleName() + "</a><ul id='li" + tree.getId()
						+ "' class='nonode'>";
			} else {
				html += "<ul><li>" + space(tree.getFloorNum()) + "<img id='img"
						+ tree.getId()
						+ "' src='images/1.jpg' onclick='showhide("
						+ tree.getId()
						+ ")'><a class='marr' href='javascript:treeClick("
						+ "\"" + tree.getRoleId() + "\"" + ")'>"
						+ tree.getRoleName() + "</a><ul id='li" + tree.getId()
						+ "' class='nonode'>";
			}
			for (int i = 0; i < tree.getChildHtml().size(); i++) {
				html += createChildHtml(tree.getChildHtml().get(i), roleId);
			}
			html += "</ul></li></ul>";
		} else {
			if (tree.getRoleId().equals(roleId)) {
				html += "<li>" + space(tree.getFloorNum())
						+ "<a style='color:red' href='javascript:treeClick("
						+ "\"" + tree.getRoleId() + "\"" + ")'>"
						+ tree.getRoleName() + "</a></li>";
			} else {
				html += "<li>" + space(tree.getFloorNum())
						+ "<a href='javascript:treeClick(" + "\""
						+ tree.getRoleId() + "\"" + ")'>" + tree.getRoleName()
						+ "</a></li>";
			}
		}
		return html;
	}

	/**
	 * 根据登录用户角色查询其下所有角色
	 */
	public List<TreeHtml> getRoleList(UserInfo userInfo) throws Exception {
		userInfo = loginMapper.getUserByName(userInfo);
		List<TreeHtml> roleList = roleMapper.getRoleById(userInfo);
		size = roleList.size();
		roleList = getFloor(roleList);
		for (int i = 0; i < roleList.size(); i++) {
			roleList.get(i).setRoleName(
					space(roleList.get(i).getFloorNum())
							+ roleList.get(i).getRoleName());
		}
		return roleList;
	}

	/**
	 * 新增角色
	 */
	public String addRole(RoleInfo roleInfo, UserInfo userInfo)
			throws Exception {
		userInfo = loginMapper.getUserByName(userInfo);
		AspnetRoles aspnetRoles = new AspnetRoles();
		aspnetRoles.setApplicationid(MessageManager.getMsg("application"));
		aspnetRoles.setRoleid(roleMapper.getUuid());
		aspnetRoles.setRolename(roleInfo.getRoleName().trim());
		aspnetRoles.setLoweredrolename(roleInfo.getRoleName().toLowerCase()
				.trim());
		aspnetRoles.setSource(Integer.parseInt(MessageManager
				.getMsg("insertSource")));
		aspnetRoles.setDescription(roleInfo.getDescription().trim());
		aspnetRoles.setParentid(roleInfo.getParentId());
		aspnetRoles.setCreatetime(new Date());
		aspnetRoles.setCustomerid(userInfo.getUserCustomId());
		aspnetRolesMapper.insertSelective(aspnetRoles);
		// TODO Auto-generated method stub
		return "新增角色成功！";
	}

	/**
	 * 根据角色id查询角色信息
	 */
	public RoleInfo getRoleByRoleId(RoleInfo roleInfo) throws Exception {
		return roleMapper.getRoleByRoleId(roleInfo.getRoleId());
	}

	/**
	 * 编辑角色提交
	 */
	public String editRole(RoleInfo roleInfo) throws Exception {
		AspnetRoles aspnetRoles = new AspnetRoles();
		aspnetRoles.setId(roleInfo.getRoId());
		aspnetRoles.setDescription(roleInfo.getDescription().trim());
		aspnetRoles.setLoweredrolename(roleInfo.getRoleName().toLowerCase()
				.trim());
		aspnetRoles.setRolename(roleInfo.getRoleName().trim());
		aspnetRoles.setParentid(roleInfo.getParentId());
		aspnetRolesMapper.updateByPrimaryKeySelective(aspnetRoles);
		return "编辑角色成功！";
	}

	/**
	 * 保存配置
	 */
	public String saveConfig(RoleInfo roleInfo) throws Exception {
		// 删除原角色对应页面按钮表
		roleMapper.deleteByRoleId(roleInfo);
		// 新增角色对应页面按钮表
		String[] pageRoleList = roleInfo.getButtonString().split(",");
		for (int i = 0; i < pageRoleList.length; i++) {
			String[] pageRole = pageRoleList[i].split("-");
			String[] page = pageRole[0].split("\\$");
			PrivilegeRolesAuthority privilegeRolesAuthority = new PrivilegeRolesAuthority();
			privilegeRolesAuthority.setRoleid(roleInfo.getRoleId());
			privilegeRolesAuthority.setMenuid(Integer.parseInt(page[1]));
			privilegeRolesAuthority.setPageoperationid(Short
					.parseShort(pageRole[1]));
			privilegeRolesAuthority.setCreatetime(new Date());
			privilegeRolesAuthority.setModifytime(new Date());
			privilegeRolesAuthorityMapper
					.insertSelective(privilegeRolesAuthority);
		}
		return "保存配置成功！";
	}

	/**
	 * 删除角色
	 */
	public MessageCommon deleteRole(RoleInfo roleInfo) throws Exception {
		MessageCommon messageCommon = new MessageCommon();
		// 根据角色id查询角色信息(获取自增长编号)
		RoleInfo roInfo = roleMapper.getRoleByRoleId(roleInfo.getRoleId());
		// 根据角色id查询其是否有下属角色
		Integer count = roleMapper.selectChildRole(roInfo.getRoId());
		// 根据角色id查询其是否有用户
		Integer customCount = roleMapper.selectCustomByRoleId(roleInfo
				.getRoleId());
		// 如果有下属角色
		if (count > 0) {
			messageCommon.setFlag(false);
			messageCommon.setMessage("删除角色失败！该角色下有子角色");
		} else if (customCount > 0) {
			messageCommon.setFlag(false);
			messageCommon.setMessage("删除角色失败！该角色下有用户");
		} else {
			aspnetRolesMapper.deleteByPrimaryKey(roInfo.getRoId());
			messageCommon.setFlag(true);
			messageCommon.setMessage("删除角色成功！");
		}
		return messageCommon;
	}
}
